package com.study.spring.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author
 * @date 2021年11月21日 20:29
 * @description
 */

@Configuration
public class ThreadConfig {


    private static final Logger logger = LoggerFactory.getLogger(ThreadConfig.class);

    @Value("${async.executor.thread.core_pool_size}")
    private int corePoolSize;
    @Value("${async.executor.thread.max_pool_size}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue_capacity}")
    private int queueCapacity;
    @Value("${async.executor.thread.name.prefix1}")
    private String namePrefix1;

    @Value("${async.executor.thread.name.prefix2}")
    private String namePrefix2;



    @Bean(name = "test1")
    public Executor asynTest1(){

        logger.info("start asyncServiceExecutor");

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new VisibleThreadPoolTaskExecutor();

        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);

        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);

        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);

        threadPoolTaskExecutor.setThreadNamePrefix(namePrefix1);

        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        threadPoolTaskExecutor.initialize();


        return threadPoolTaskExecutor;

    }


    @Bean(name = "test2")
    public Executor asynTest2(){

        logger.info("start asyncServiceExecutor");

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new VisibleThreadPoolTaskExecutor();

        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);

        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);

        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);

        threadPoolTaskExecutor.setThreadNamePrefix(namePrefix2);

        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;

    }


}
